// JavaScript Document
var rmoney = '';
jQuery.support.placeholder = (function(){
    var i = document.createElement('input');
    return 'placeholder' in i;
})();

$(window).on('beforeunload', function (e) {  
    v = $('#nos').val(); 
    if (v == 0) {
        //	$.blockui();			
        //return 'All your entered data will lost and you may need to reenter again';
        localStorage.setItem('formData', true);
        var elem = $('#formApp').find(':input,select,textarea'); 
        elem.each(function (index, element) {
            if ($(element).val()) { 
                if ($(element).attr('type') != 'text' && !$(element).is('select') && !$(element).is('textarea') && $(element).attr('type') != 'hidden') {
                    localStorage.setItem($(element).attr('name'), $("input[name='" + $(element).attr('name') + "']:checked").val());
                } else {
                    localStorage.setItem($(element).attr('name'), $(element).val()); 

                }
            }
        });
        return "Please Confirm"; 
    }
});

/*$(window).on('load', function () {

    if (localStorage.getItem("formData")) {
        var elem = $('#formApp').find(':input,select,textarea');
        elem.each(function (index, element) {
            var vval = localStorage.getItem($(element).attr('name'));
            //localStorage.removeItem( $(element).attr('name') );
            if (vval) {

                if ($(element).attr('type') != 'text' && !$(element).is('select') && !$(element).is('textarea') && $(element).attr('type') != 'hidden') {

                    //$(element).removeAttr("checked");  
                    var $radios = $('input[name*="' + $(element).attr('name') + '"]');
                    $radios.filter('[value="' + vval + '"]').prop('checked', true).trigger("click").trigger('change').trigger('blur');



                } else {
                    $(element).val(vval).trigger("change").trigger("blur");
                }

            }
 

        });
        localStorage.clear();
    }

    $.unblockUI();
});*/


function makeNumber(strnum) {
    if (strnum != "" || strnum !== "undefined") {
        return Number(strnum.replace(/[^0-9\.]+/g, ""))
    }
    else {
        return '';
    }
}

function toCurrency(num) {

    if (num != '' || num !== "undefined") {
        num = num.toString();
        return num.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    else {
        return '';
    }
}

function getIEversion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function showpurposedetails(value) {
    //alert (value);
    if (value != "") $("#purposeRow").show(300).removeClass('wizard-ignore').removeAttr('disabled')
    else $("#purposeRow").hide(300).addClass('wizard-ignore').attr('disabled', 'disabled');
}

function nameMerge(ID) {
    var name = $('#' + ID).val();
    var applicant = ID.charAt(ID.length - 1);
    if (applicant == 1)
    //alert ("1");
    $('.app1').text(name);
    else $('.app2').text(name);
    //alert (name);
}

function totalbikeVehicle() {
    return makeNumber($('#nob').val()) + makeNumber($('#nov').val());

}

function totalNoAssets() {
    return makeNumber($('#nob').val()) + makeNumber($('#nov').val()) + makeNumber($('#Aop').val());
}

function primaryAddress() {

    $('#Property1Address').val($('#ResidentialAddress1').val());
    $('#Property1Suburb').val($('#Suburb1').val());
    $('#Property1State').val($('#State1').val());
    $('#Property1Postcode').val($('#Postcode1').val());
}

function mortgageUpdate(i) {
    $('#MortgageOwing' + i).val(makeNumber($('#Property' + i + 'Debt1st').val()));
    $('#MortgageBank' + i).val($('#Property' + i + 'Bank').val());
}

function assetUpdate(i) {
    $('#Property' + i + 'Debt1st').val(makeNumber($('#MortgageOwing' + i).val()));
    $('#Property' + i + 'Bank').val($('#MortgageBank' + i).val());
}

function totalincomeCalculation() {
    var w=52/12;
	var f=26/12;
	
    var workIncome1 = makeNumber($('#IncomeAfterTax1').val());
    var p1 = $('#IncomeAfterTax1Period').val();
    if (p1 == "Weekly") p1 = w;
    else if (p1 == "Fortnightly") p1 = f;
    else if (p1 == "Monthly") p1 = 1;
    else p1 = 0;   
	var centerlinkIncome1 = makeNumber($('#CentrelinkIncome1').val());
	var otherIncome1 = makeNumber($('#RentalIncome1').val());
	var ois1= $('#OtherIncomeSpecify1').val();
	var oip1= $('#OtherIncomePeriod1').val();
	if (oip1 == "Weekly") otherIncome1=otherIncome1*w;
    if (oip1 == "Fortnightly") otherIncome1=otherIncome1*f;
	if(ois1=="Parent income" || ois1=="Spouse income" || ois1=="Child Support(Private)" || ois1=="Private arrangement") otherIncome1=0;
	var totalIncome1 = parseInt(workIncome1 * p1 + centerlinkIncome1 * f + otherIncome1);

    var workIncome2 = makeNumber($('#IncomeAfterTax2').val());
    var p2 = $('#IncomeAfterTax2Period').val();
    if (p2 == "Weekly") p2 = w;
    else if (p2 == "Fortnightly") p2 = f;
    else if (p2 == "Monthly") p2 = 1;
    else p2 = 0;
    var centerlinkIncome2 = makeNumber($('#CentrelinkIncome2').val());
    var otherIncome2 = makeNumber($('#RentalIncome2').val());
	var ois2= $('#OtherIncomeSpecify2').val();
	var oip2= $('#OtherIncomePeriod2').val();
	if (oip2 == "Weekly") otherIncome2=otherIncome2*w;
    if (oip2 == "Fortnightly") otherIncome2=otherIncome2*f;
	if(ois2=="Parent income" || ois2=="Spouse income" || ois2=="Child Support(Private)" || ois2=="Private arrangement") otherIncome2=0;
    var totalIncome2 = parseInt(workIncome2 * p2 + centerlinkIncome2 * f + otherIncome2);

    $("#TotalIncome").val(totalIncome1 + totalIncome2);
}

function totalpaymentCalculation() {
    var n = $("#Aop").val(); //alert (n);
    var total = 0;
    if (n >= 1) {
        var m1 = makeNumber($('#MortgagePayment1').val()); //alert (m1);
        total += m1;
    }
    if (n >= 2) {
        var m2 = makeNumber($('#MortgagePayment2').val()); //alert (m2);
        total += m2;
    }
    if (n >= 3) {
        var m3 = makeNumber($('#MortgagePayment3').val()); //alert (m3);
        total += m3;
    }
    if (n >= 4) {
        var m4 = makeNumber($('#MortgagePayment4').val()); //alert (m4);
        total += m4;
    }

    var personalloan = makeNumber($('#PersonalLoanPayment').val());
    total += personalloan;
    var creditcard = makeNumber($('#CreditCardPayment').val());
    total += creditcard;
    var paydayloan = makeNumber($('#PaydayLoanPayment').val());
    total += paydayloan;
    //alert (total);
    var n = $("#nol").val(); //alert (n);
    if (n >= 1) {
        var o1 = makeNumber($('#OtherLoanPayment1').val()); //alert (m1);
        total += o1;
    }
    if (n >= 2) {
        var o2 = makeNumber($('#OtherLoanPayment2').val()); //alert (m2);
        total += o2;
    }
    if (n >= 3) {
        var o3 = makeNumber($('#OtherLoanPayment3').val()); //alert (m3);
        total += o3;
    }
    if (n >= 4) {
        var o4 = makeNumber($('#OtherLoanPayment4').val()); //alert (m4);
        total += o4;
    }

    //total=total+personalloan+carloan+creditcard+paydayloan;
    $('#TotalPayment').val(total);


}

function repaymentCheck() {
    var v = $('#Repayment1').val();
    var p = $('#Repayment1Period').val();
    if (p == "Weekly" && v < 38) {
        alert("Please note the minimum repayment per week is $38, in order to be eligible to proceed repayment must be sufficient. If you are not comfortable with the minimum repayment, please DO NOT proceed with this application. Thank you.");
        $('#Repayment1').addClass('error');
    }
    if (p == "Fortnightly" && v < 75) {
        alert("Please note the minimum repayment per forrnight is $75, in order to be eligible to proceed repayment must be sufficient. If you are not comfortable with the minimum repayment, please DO NOT proceed with this application. Thank you.");
        $('#Repayment1').addClass('error');
    }
    if (p == "Monthly" && v < 163) {
        alert("Please note the minimum repayment per month is $163, in order to be eligible to proceed repayment must be sufficient. If you are not comfortable with the minimum repayment, please DO NOT proceed with this application. Thank you.");
        $('#Repayment1').addClass('error');
    }

}

function abn(){
	var searchtext=$('#BusinessName').val();// alert(searchtext);
	var str="http://www.abr.business.gov.au/SearchByName.aspx?SearchText="+searchtext;
	window.open(str);
}

function resetbizstage(){
	$("#businessStage").val('');
	$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
	if (wizard) {
        $('#formApp').formwizard('update_steps')
    }
}


function assetValidate(obj) {



    if (obj == 'assetLiability') {




        var aop = $('#Aop').val();
        var nov = $('#nov').val();
        var nob = $('#nob').val();

        var tbodya = [];
        tbodya.shift();

        if (aop > 0) {

            tbodya.push('.recontainer:visible tbody');

        }

        if (nov > 0) {
            tbodya.push('.mvcontainer:visible tbody');
        }

        if (nob > 0) {
            tbodya.push('.bikeContainer:visible tbody');

        }

        var tbody = tbodya.join(',');

        //alert('total no of tbody ' +$(tbody).length);
        //var tbody =$($.merge(tbody1,tbody2,tbody3));
        $(tbody).show({
            duration: 1
        }).find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

        if ($('#myHomeField1').is(':hidden')) {
            $('#myHomeField1').find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
        }



        //$('tbody','#assetsTable').show();
        var noErr = 0;
        var tErr = 0;
        var newTbody = [];
        newTbody.shift();

        $(tbody).each(function (rowIndex, erow) {


            e = $(erow).find('input,select');

            //alert(e.length); 
            //alert($(e).attr('class'));

            e.each(function (index, el) {

                //if (!$("#formApp").validate().element(el)) {
                if (!$(el).valid()) {
                    noErr = noErr + 1;
                }


            });


            //alert(rowIndex +'has '+ noErr);
            if (noErr > 0) {
                tErr = tErr + 1;
            } else {
                $(erow).hide(1);
            }


        });



        if (tErr > 0) {
            //$("#formApp").formwizard("back"); 
            //$(newTbody).show({duration:1});
            return false;

        } else {
            return true;
        }

    }
/*else if(obj=='IncomeExpense'){
		
		if(!$('#ExitStrategy1').val()){
		
		
			$('#multiExit').addClass(error);
			
			return false;
		}else{
			$('#multiExit').removeClass(error);
			return true;
		}
		
		
	}*/
    else {
        return true;
    }

}

function investmentCalc() {


    var InvestmentValuea = '';
    var InvestmentAmountOwinga = '';
    var InvestmentPaymentavalue = '';
    var InvestmentBanka = '';
    var InvestmentOwnera = '';
    var PropertyaAddress = '';
    var PropertyaState = '';
    var PropertyaPostcode = '';
    var PropertyaDebt1st = '';
    var PropertyaDebt2nd = '';
    var PropertyaCaveat = '';
    var PropertyaType = '';
    //$("#PropertyaTypeOther").value+="|"+$("#Property"+i+"TypeOther").value
    var PropertyaDescription = '';
    var PropertyaBedrooms = '';
    var PropertyaBathrooms = '';
    var PropertyaLandSize = '';
    var morarra = '';
    var monarra = '';
    var LVRpa = '';
    var propertyValTotal = 0;
    var propertyPayTotal = 0;
    var n = $('#nov').val();
    var pl = $('#Aop').val();

    if (n != '') {

    }

    if (pl != '') {



        for (i = 1; i <= pl; i++) {


            $('#Property' + i + 'AmountOwing').val(makeNumber($("#Property" + i + "Debt1st").val()) + makeNumber($("#Property" + i + "Debt2nd").val()) + makeNumber($("#Property" + i + "Caveat").val()));
            if (makeNumber($("#Property" + i + "Value").val()) != 0 || $("#Property" + i + "Value").val() != '') {
                $("#LVRp" + i).val(parseInt(makeNumber($('#Property' + i + 'AmountOwing').val()) * 100 / makeNumber($("#Property" + i + "Value").val())) + "%");
            }
            else {
                $("#LVRp" + i).val('0%');
            }

            propertyValTotal = propertyValTotal + makeNumber($("#Property" + i + "Value").val());
            propertyPayTotal = propertyPayTotal + makeNumber($("#Property" + i + "Payment").val());



            if (i == 2) {
                InvestmentValuea = $("#Property2Value").val();
                InvestmentAmountOwinga = $('#Property2AmountOwing').val();
                InvestmentPaymentavalue = $("#Property2Payment").val()
                InvestmentBanka = $("#Property2Bank").val();
                InvestmentOwnera = $("#Property2Owner").val();
                PropertyaAddress = $("#Property2Address").val();
                PropertyaState = $("#Property2State").val();
                PropertyaPostcode = $("#Property2Postcode").val();
                PropertyaDebt1st = $("#Property2Debt1st").val();
                PropertyaDebt2nd = $("#Property2Debt2nd").val();
                PropertyaCaveat = $("#Property2Caveat").val();
                PropertyaType = $("#Property2Type").val();
                //$("#PropertyaTypeOther").value = $("#Property"+i+"TypeOther").value
                PropertyaDescription = $("#Property2Description").val();
                PropertyaBedrooms = $("#Property2Bedrooms").val();
                PropertyaBathrooms = $("#Property2Bathrooms").val();
                PropertyaLandSize = $("#Property2LandSize").val();

                morarra = $("input:radio[name=morarr2]:checked").val();
                monarra = $("mon2arr").val();
                LVRpa = $("#LVRp2").val();
            }


            if (i > 2) {
                InvestmentValuea += "|" + $("#Property" + i + "Value").val();
                InvestmentAmountOwinga += "|" + (makeNumber($("#Property" + i + "Debt1st").val()) + makeNumber($("#Property" + i + "Debt2nd").val()) + makeNumber($("#Property" + i + "Caveat").val()));
                InvestmentPaymentavalue += "|" + $("#Property" + i + "Payment").val()
                InvestmentBanka += "|" + $("#Property" + i + "Bank").val();
                InvestmentOwnera += "|" + $("#Property" + i + "Owner").val();
                PropertyaAddress += "|" + $("#Property" + i + "Address").val();
                PropertyaState += "|" + $("#Property" + i + "State").val();
                PropertyaPostcode += "|" + $("#Property" + i + "Postcode").val();
                PropertyaDebt1st += "|" + $("#Property" + i + "Debt1st").val();
                PropertyaDebt2nd += "|" + $("#Property" + i + "Debt2nd").val();
                PropertyaCaveat += "|" + $("#Property" + i + "Caveat").val();
                PropertyaType += "|" + $("#Property" + i + "Type").val();
                //$("#PropertyaTypeOther").value+="|"+$("#Property"+i+"TypeOther").value
                PropertyaDescription += "|" + $("#Property" + i + "Description").val();
                PropertyaBedrooms += "|" + $("#Property" + i + "Bedrooms").val();
                PropertyaBathrooms += "|" + $("#Property" + i + "Bathrooms").val();
                PropertyaLandSize += "|" + $("#Property" + i + "LandSize").val();
                morarra += "|" + $("input:radio[name=morarr2]:checked").val();;
                monarra += "|" + $("mon" + i + "arr").val();
                LVRpa += "|" + $("#LVRp" + i).val();
            }


        }
        alert(propertyPayTotal);



        // all values
        $('#InvestmentValuea').val(InvestmentValuea);
        $("#InvestmentAmountOwinga").val(InvestmentAmountOwinga);
        $("#InvestmentPaymentavalue").val(InvestmentPaymentavalue);
        $("#InvestmentBanka").val(InvestmentBanka);
        $("#InvestmentOwnera").val(InvestmentOwnera);
        $("#PropertyaAddress").val(PropertyaAddress);
        $("#PropertyaState").val(PropertyaState);
        $("#PropertyaPostcode").val(PropertyaPostcode);
        $("#PropertyaDebt1st").val(PropertyaDebt1st);
        $("#PropertyaDebt2nd").val(PropertyaDebt2nd);
        $("#PropertyaCaveat").val(PropertyaCaveat);
        $("#PropertyaType").val(PropertyaType);
        $("#PropertyaDescription").val(PropertyaDescription);
        $("#PropertyaBedrooms").val(PropertyaBedrooms);
        $("#PropertyaBathrooms").val(PropertyaBathrooms);
        $("#PropertyaLandSize").val(PropertyaLandSize);
        $("#morarra").val(morarra);
        $("#monarra").val(monarra);
        $("#LVRpa").val(LVRpa);


    }

}

var elem;

function removeProperty(elem) {
    var Id = elem.attr('id');
    var j = Id.substr(Id.length - 1);
    var n = j - 1

    if (n < 6) {
        $('#addmoreproperty:hidden').show();
    }

    if (n >= 1) {

        elem.closest('table').remove();
        $('.mortgageContainer:last').remove();
        $('#Aop').val(n);

        $('.recontainer:last .propertyClose').show();


    }

    else {

        elem.closest('table').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
        $('.mortgageContainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
        $('#propertyHead').hide();
        $('#Aop').val(0);

    }
}


//init page main function


function InitPage() {
    $('#item1', '#sidenav').addClass('active');
	$('div:nth-child(2)', '#StepHead').addClass('legend step1');
    //$('#back').hide().attr('disabled', 'disabled');
 	$('#back').css("visibility","hidden").attr('disabled', 'disabled');
    $('#nos').val(0);

    //	$(".fieldrow:odd").addClass('oddRow');
    //	$(".fieldrow:even").addClass('evenRow');
    $("#applicantconfirm,#exApplicant,.boardingWith,.applicant2,.bikeContainer:last,.vehicleBank,.vehiclePayment,#purposeRow,#BoardingRentingFeeRow1,#BoardingRentingFeeRow2,#hasdirectors,#myHomeField1,.monarrmonths,.employmenttype,.businessDirectors,.selfEmployee,.directorNames,.stageOfProperty,.stageOfRefinance,.otherSpecify,.expenseDetails,.p1app1title").hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", "disabled"); //wizard-ignore tells the wizard to not touch the input fields

	$('#PurposeOfLoan1, #TypeOfEmployment1, #OtherPurpose, #CreditHistory1, #ExitStrategy1 ').val('');
	$('.usbrow').hide();

}



$(function () {
	
	$('#noassetwarning').hide();
	$('.usbrow').hide();
	//localStorage.clear();
   $('#bottomBtns').show();
    var wizard = 1;
   // $.blockUI();



    $("#progressbar").progressbar({
        value: 10
    });


    $('input[name=NumberPeopleApplying]').click(function () {
        if (this.checked && $(this).val() == 1) {
            $("#applicantconfirm").hide(300).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled').removeAttr('checked');


            $('.applicantInfo').removeClass('column');
            $('.applicantInfo .part').addClass('column');
            $('.applicant2').removeClass('column').fadeOut(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
            $("#exApplicant").hide(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
        }
        else {
            $("#applicantconfirm").show(300).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled")
        }
        if (wizard) $('#formApp').formwizard('update_steps');

    });


/*$("#NumberPeopleApplying_0").click(function() { 
		
		$("#applicantconfirm").hide(500).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled").removeAttr("checked").removeClass('error');
		$('.applicantInfo').removeClass('column');
		$('.applicantInfo .part').addClass('column');
		$('.applicant2').removeClass('column').fadeOut(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
		$("#exApplicant").fadeOut(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');


		//$("#formApp").formwizard("update_steps");
	});
	$("#NumberPeopleApplying_1").click(function() {
		$("#applicantconfirm").fadeIn(1000).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");




	});
*/


   $('input[name=Filledform]').click(function () {
        //alert($(this).val());
        if (this.checked && $(this).val() == 'Yes') {
            $("#exApplicant").show(300).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");
            $(".applicant2").removeClass('column').hide(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled");
            $('.applicantInfo').removeClass('column');
            $('.applicantInfo .part').addClass('column');
			$('#woman').show();
			$('.p1app1title').text('').hide();
			$('.p2app1title').text('Personal Informaion');
        }
        else if ($(this).val() == 'No') {
            $("#exApplicant").hide(300).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled').removeClass('error');
            $('.applicantInfo').addClass('column');
            $('.applicantInfo .part').removeClass('column');
            $('.applicant2').addClass('column').show(1000).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");
			$('#woman').hide();
			$('.p1app1title').text("Applicant 1's Personal Information").show();
			$('.p2app1title').text("Applicant 1's Personal Information");
        }
        if (wizard) $('#formApp').formwizard('update_steps');

    });
	
	
	
$("#FilledformNo").click(function() {
	$('#noassetwarning').hide();
	$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
	$('#assetsTable tr:first').show();
	$('.mvcontainer:hidden,  .vehicleClose').show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
	if (wizard) $('#formApp').formwizard('update_steps');
})
/*$("#FilledformYes").on("click", function() {
		$("#exApplicant").fadeIn(1000).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");
		$(".applicant2").removeClass('column').hide(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled");
		$('.applicantInfo').removeClass('column');
		$('.applicantInfo .part').addClass('column');
		//$("#formApp").formwizard("update_steps");
	});
	$("#FilledformNo").click(function() {
		$("#exApplicant").fadeOut(1000).find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
		$('.applicantInfo').addClass('column');
		$('.applicantInfo .part').removeClass('column');
		$('.applicant2').addClass('column').show(1000).find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");

		//$("#formApp").formwizard("update_steps");

	})
	
*/
	$("#FilledformYes").on("click", function() {
		$('.app1pinfo').text(2);	
	})
	$("#FilledformNo, #NumberPeopleApplying_0").on("click", function() {
		$('.app1pinfo').text(1);	
	})
	
    $('#LoanAmount').on("blur", function () {
        var v = $(this).val();
		v=makeNumber(v);
        if (v < 1600) {
            //$(this).closest('.field').append("<label class='error'>The minimum loan amount is $1000</label>");
            $('#laWarning').html(" The minimum loan amount is $1600");
			$(this).val(1600);
        } else {
            //$(this).closest('.field').children('label.error').remove();
            $('#laWarning').html("");
        }
    })

    $('#PurposeOfLoan1').on("change", function () {

        var purpose = $(':selected', this);
        var n = $('#Aop').val();

        if (purpose.val() != "") {
            $("#purposeRow").show(300).find('textarea').removeClass('wizard-ignore').removeAttr('disabled')
        } else {
            $("#purposeRow").hide(300).find('textarea').addClass('wizard-ignore').attr('disabled', 'disabled').removeClass('error');
        }



        var ptype = purpose.closest('optgroup').attr('label');
        var ptext = $('#OtherPurpose').val();
        var prefix = "The business purpose intended for this loan is ";

        if (ptype == "Business") {

            ptext = $('#OtherPurpose').val();
			ptext = ptext.replace("The Business Purpose Intended For This Loan Is ", "");
            prefix = "The business purpose intended for this loan is ";

            if (ptext.indexOf(prefix) == -1) {

                $('#OtherPurpose').val(prefix + ptext).valid();

            }
            $('#loanLabel1').text('Business Loan 1');
            $('#loanLabel2').text('Business Loan 2');

            for (i = 1; i <= n; i++) {
                $('#MortgagePayment' + i).removeClass('required').valid();
            }

            $('#LivingExpenses').removeClass('required').valid();
           // $('.businessDetails').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

            $('.expenseDetails,.employmentDetails').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');




        }
        else if (ptype == "Personal") {

            ptext = $('#OtherPurpose').val();
            prefix = "The business purpose intended for this loan is";
            if (ptext.indexOf(prefix) != -1) {
                $('#OtherPurpose').val('');
            }



            for (i = 1; i <= n; i++) {
                $('#MortgagePayment' + i).addClass('required').valid();
            }
            $('#loanLabel1').text('Personal Loan');
            $('#loanLabel2').text('Payday Loan');
            $('#LivingExpenses').addClass('required').valid();
            $('.expenseDetails,.employmentDetails').show(1000).find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

          //  $('.businessDetails').hide(1000).find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');


        }
        else if (ptype == '' || ptype === undefined) {

            // $('.employmentDetails').hide();
           // $('.employmentDetails,.businessDetails').hide(1000).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
        }


        if (wizard) $('#formApp').formwizard('update_steps');

    });


	/*$('#ResidentialAddress1').autocomplete({
				source: "addressify.php", 
				minLength: 3, 
				select: function (event, obj) {
				
				$.getJSON('http://localhost/morgancash/getParsedAddress.php?term='+ obj.item.value, function(data) {	
				
		
			
			$('#ResidentialAddress1').val(data.StreetLine+', '+data.Suburb+' '+data.State+' '+data.Postcode);
			//alert(data.StreetLine);
			
			$('#Suburb1').val(data.Suburb);
			$('#State1').val(data.State);
			$('#Postcode1').val(data.Postcode);
			$('#Number1').val(data.Number);
			$('#Street1').val(data.Street);
			$('#StreetType1').val(data.StreetType);
			$('#addressicon').show();
			});
				}
	 });*/

    $('#ResidentialStatus1,#ResidentialStatus2').on("change", function () {
        val = $(this).val();
        Id = $(this).attr('id');
        i = Id.substr(Id.length - 1);

        if (val == 'boarding') {
            
            $('.boardingRow').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
        }
        else if (val == 'renting') {
           
            $('.boardingRow').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
        }
        else {
          
            $('.boardingRow').hide().find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');;
        }

        if (wizard) {
            $('#formApp').formwizard('update_steps')
        }

    });

    $('#ResidentialStatus1').change(function () {
        var v = $(this).val();
        if (v == "boarding" || v == "renting") {
            if ($('#Aop').val() > 0) {

                removeProperty($('#propertyx1'));
                
            }

            
        } else {
            
            if ($('#Aop').val() < 1) {
                $('#addmoreproperty').trigger('click');
            }

        }
		if(v == "I own my home outright"){
			$('#Property1Debt1st').val(0);
			$('#Property1Bank').val('none');
			$('#MortgagePayment1').val(0);
		}else{
			$('#Property1Debt1st').val('');
			$('#Property1Bank').val('');
			$('#MortgagePayment1').val('');
			
		}
		
		
        if (wizard) $('#formApp').formwizard('update_steps');
    });

	$('#BoardingRentingFee1,#BoardingRentingFee2').blur(function(){
		var boardingFee1 = makeNumber($('#BoardingRentingFee1').val());
		var boardingFee2 = makeNumber($('#BoardingRentingFee2').val());
		var totalBF = boardingFee1+boardingFee2;
		
		$('#boardingRentingFee').val(totalBF); 
		
	});

    $('.Phone').blur(function (e) {

        iD = $(this).attr('id');
        var i = iD.substr(iD.length - 1);
        $('#Mobile' + i).valid();


    });		
	
	
	
    $('.Mobile').blur(function (e) {
        id = $(this).attr('id');
        var i = id.substr(id.length - 1);
        $('#Phone' + i).valid();

    });
	
	
	/*$('.Postcode ').blur(function (e) {
        id = $(this).attr('id');
        $('#Postcode1').valid();

    });*/
	

/*

	$(document).on("keyup", '.Phone', function() {

		$(this).val(function(i, val) {

			val = val.replace(/[^.0-9\s]/, "");
			if (val.length == 1) {
				val = 0;
			}
			else if (val.length == 2) {
				val = val + " ";
			}
			else if (val.length == 7) { 
				val = val + " ";
			}

			return val;

		});
	});



	$(document).on('keyup', '', function() {

		$(this).val(function(i, val) {

			val = val.replace(/[^0-9\s]/, "");

			if (val.length == 4) {
				val = val + " ";
			}
			else if (val.length == 8) {
				val = val + " ";
			}

			return val;

		});
	});
	
	
	
	

	$(document).on("blur", '.Phone', function() {
		val = $(this).val();

		if (val.length <= 10) {

			if (!val.match(/^[0][0-9]\s\d{3}\s\d{5}$/)) {
				if (val.charAt(0) != 0) {
					p1 = "0" + val.charAt(0);
				}
				else {

					p1 = val.charAt(0) + val.charAt(1);
				}
				p2 = val.substr(1, 3);
				p3 = val.substr(4, 11);
				val = p1 + " " + p2 + " " + p3;
				$(this).val(val);
			}

		}

	});

	$(document).on("blur", '', function() {
		val = $(this).val();
		if (val.length <= 10) {
			if (!val.match(/^\d{4}\s\d{3}\s\d{3}$/)) {
				p1 = val.substring(0, 4);
				p2 = val.substring(4, 7);
				p3 = val.substring(7, 11);
				val = p1 + " " + p2 + " " + p3;
				$(this).val(val);
			}

		}
 
	});
	
*/
/*jQuery(function($) {
    $("#test").mask("9?9", {placeholder:" "});
});
*/

/*var options =  {maxlength: false,onKeypress: function(cep){
  var masks = ['9999 9999', '99 9999 9999'];
    mask = (cep.length>=8) ? masks[1] : masks[0];
  $('.Phone').mask(mask,this);
 
}};*/

$('.Phone').mask('99 9999 9999', {reverse: true});


$('.Phone').on('focusout', function(){
	value =$(this).val(); 
	tlength = value.length;
	
	
});


   // $('.Phone').mask('99 9999 9999');
    $('.Mobile').mask('9999 999 999');

	//$('.capitalize').mask('<<');   
	
	function ucwords(str,force){
    str=force ? str.toLowerCase() : str;
    return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,
    function(firstLetter){
    return firstLetter.toUpperCase();
    });
}

    $(document).on("blur", '.capitalize', function () {

        val = ucwords($(this).val(),true);
       // val = val.charAt(0).toUpperCase() + val.substring(1);
        $(this).val(val);

    });


/*    $(document).on("blur", '.capitalize', function () {

        val = $(this).val();
        val = val.charAt(0).toUpperCase() + val.substring(1);
        $(this).val(val);

    });
	*/
	
	$('.currency').mask('000,000,000,000,000,000', {reverse: true});
	
	   /* $(document).on("blur", '.currency', function () { 

        val = makeNumber($(this).val());
        //val = (val/1000).toFixed(3);
        val = toCurrency(val);
        if (val == 0) $(this).val('');
        else $(this).val(val);
    });

    $*/

    $('#ResidentialAddress1,#Suburb1,#State1,#Postcode1').blur(function () {
        primaryAddress()
		
    });

    $('#Residency1').change(function () {
        var opt = $(this).val();
        if (opt == 'Working Visa (457)') {
            $('#visaDialog').dialog('open');
        }
    })


  
///Second DatePicker

 $('#DateOfBirth').focusin(function (e) {
									
        $('#ui-datepicker-div').bgiframe();
    });

    $("#DateOfBirth").datepicker({ 
        dateFormat: 'dd/mm/yy',
        changeYear: true,
        changeMonth: true,
        yearRange: '-90y:-18y',
        defaultDate: '-33y',
        maxDate: "-18y",
        minDate: "-90y",
        showMonthAfterYear: true,
        showOn: 'both',
        buttonImageOnly: true,
		
        buttonImage: 'account/images/ui-calendar-icon.png',
        beforeShow: function (inst) {


            //$('#ui-datepicker-div').bgifrmae();
        },
        onClose: function () {

            $(this).valid();
        },
		onChangeMonthYear: function(year, month, inst){
			curDate = $.datepicker.formatDate('dd', new Date());
			actDate = $.datepicker.formatDate('dd',$(this).datepicker( "getDate" ));
			if(actDate){
			var newD = actDate+'/'+month+'/'+year; 
			}else{
			var newD = curDate+'/'+month+'/'+year; 
			}
			$(this).datepicker( "setDate", newD); 
        }

    });

    //vehicle table

   /* var mvhtml = ($('.mvcontainer:last').html());
    $('.mvcontainer:last').html(mvhtml.replace(/{n}/g, '1'));
    //$('#vechilex1').hide();
    $('#nov').val(1);*/


    $('#addmorevehicle').click(function (e) {
		$('#noassetwarning').hide();
		$('#businessStage').val('');
		$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
		
        var obj = $('.mvcontainer:last');
        var nma = totalbikeVehicle();
        if ($('.mvcontainer:hidden').length) {
            $('.mvcontainer:hidden').show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
            $('#nov').val(1)
        }
        else {
            var j = $('.mvcontainer').length;
            var n = j + 1;
            if (n <= 4 || nma <= 3) {
                var newHtml = mvhtml.replace(/{n}/g, n);
                obj.clone().html(newHtml).appendTo('#vechicleHolder');

                $('#nov').val(n);
            }

            if (n > 3) {
                $(this).hide();
            }


            if (nma >= 3) {

                $('#addbike,#addmorevehicle').hide();
            }

        }
        if (!wizard) $('.mvcontainer:last tbody').show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

        var nma = totalbikeVehicle();

        if (nma < 1) {
            $('#assetsTable tr:first').hide();
        }
        else {
            $('#assetsTable tr:first').show();
        }


        $('.mvcontainer .vehicleClose').hide();

        $('.mvcontainer:last .vehicleClose').show();
        

    });



    //bike table

    /*var bikehtml = ($('.bikeContainer:last').html());

    //$('#bikex1').hide();
    $('.bikeContainer:last').html(bikehtml.replace(/{n}/g, '1'));

    //$('#bikex1').hide();
    $('#nob').val(0);*/


    $('#addbike').click(function (e) {
		$('#noassetwarning').hide();
		$('#businessStage').val('');
		$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
		
        $(this).hide();
        $(".bikeContainer").show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
        $('#nob').val(1);




        var nma = totalbikeVehicle();

        //alert(nma);
        if (!wizard) $('.bikeContainer:last tbody').show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

        if (nma < 1) {
            $('#assetsTable tr:first').hide();
        }
        else {
            $('#assetsTable tr:first').show();
        }

        
    });




    $(".morebtn").button().click(function (event) {
        event.preventDefault();
		//resetbizstage();
    });



/*
    var rehtml = ($('.recontainer:last').html());
    var morghtml = $('.mortgageContainer:last').html();
    $('.recontainer:last').html(rehtml.replace(/{n}/g, '1'));
    $('.mortgageContainer:last').html(morghtml.replace(/{n}/g, '1'));*/



    //$('#propertyx1').hide();
    $('#Aop').val('1');

    $('#addmoreproperty').click(function (e) {
		$('#noassetwarning').hide();
		$('#businessStage').val('');
		$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
		
        var obj = $('.recontainer:last');
        var mortgage = $('.mortgageContainer:last');
        if ($('.recontainer:hidden').length) {
            $('.recontainer:hidden').show().find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");
            $('#propertyHead').show();
            $('.mortgageContainer:last').show().find(":input,textarea,select").removeClass("wizard-ignore").removeAttr("disabled");;
            $('#Aop').val('1');

        }
        else {
            var j = $('.recontainer').length;
            var n = j + 1;
            if (n <= 6) {
                var newHtml = rehtml.replace(/{n}/g, n);
                newHtml = newHtml.replace(/{m}/g, 1);
                newMortgage = morghtml.replace(/{n}/g, n);
                obj.clone().html(newHtml).appendTo('#reHolder');
                mortgage.after(mortgage.clone().html(newMortgage));

                $('#Aop').val(n);
                if (wizard) {
                    $('tbody', '.recontainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
                }
            }
            if (n > 5) {
                $(this).hide();
            }
            $("#myHometd" + n).hide();
        }


        $('.recontainer .propertyClose').hide();
        $('.recontainer:last .propertyClose').show();
        
    });

    //show hide address
    $('input[name=myHome]').click(function () {
        if (this.checked && $(this).val() == 'Yes') {
            $("#myHomeField1").hide(300).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
        } else {
            $("#myHomeField1").show(300).find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled').val('');
        }
        
    });

    //add more assets single function

    $('#assetsTable').on('click', '.rowCollapse', function () {
        //$(this).parents('thead').next('tbody').slideToggle('slow'); 
        if (wizard) {
            crow = $(this).parents('thead').next('tbody');

            $(this).closest('.rowHolder').find('tbody:visible').not(crow).hide(500);
            var noErr = 0;
            var nowShow = $(this).closest('#assetsTable').find('tbody:visible:not(:first)').not(crow);
/*            if (nowShow.length > 0) {
                e = nowShow.find('input,select,textarea');


                e.each(function (index, el) {

                    if ($("#formApp").validate().element(el) == false) {
                        noErr = noErr + 1;
                    }

                });


            }
*/            if (noErr == 0) {
                crow.toggle(function(){
				if(crow.is(':visible')){
					crow.show().find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
				}else{
					crow.hide(500).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
				}
				});
				nowShow.hide(500).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');


            }

            if (wizard) $('#formApp').formwizard('update_steps')
        }
    })


    $('#assetsTable').on('focus', '.rowShow', function () {
        if (wizard) {

            obj = $(this).parents('thead').next('tbody:hidden');
            state = $(this).parents('thead').next('tbody').is(':hidden');
            var noErr = 0;
            var nowShow = $(this).closest('#assetsTable').find('tbody:visible:not(:first)').not(obj);
            if (nowShow.length > 0) {
                e = nowShow.find('input,select,textarea').not('.wizard-ignore');
            }

            if (state) {


                obj.show(500).find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
                nowShow.hide(500).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
                //$(this).parents('thead').find('.rowCollapse').addClass('open',500);
                //alert($(this).closest('.rowHolder').find('tbody:visible').length); 




            }




            if (wizard) $('#formApp').formwizard('update_steps')
        }

    })



   $('#assetsTable').on('click', '.vehicleClose', function () {

		var nPA = $('input[name=NumberPeopleApplying]:checked').val();
		var Filledform = $('input[name=Filledform]:checked').val();
		var assets = totalNoAssets();

		var allowRemove = false;
		
		
		if(totalNoAssets()>>1){
			allowRemove = true; 
		}else{
			if (nPA == 2 && Filledform =='Yes'){
			allowRemove = true;
		}
		}
		
		
		  

        if (allowRemove) {

                var Id = $(this).attr('id');
                var j = $('.mvcontainer').length;
                var n = j - 1;




                if (n >= 1) {
                    $(this).closest('table').remove();
                    $('#nov').val(j - 1);
                    //if(n>1){
                    $('.mvcontainer:last .vehicleClose').show();
                    //}
                }
                else {

                    $(this).closest('table').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
                    $('#nov').val(0);
                    $('.mvcontainer:last .vehicleClose').hide();
                }


                var nma = totalbikeVehicle();

                //alert(nma);
                if (n < 4) {
                    $('#addmorevehicle:hidden').show();
                }

                if (nma <= 3) {
                    $('#addmorevehicle:hidden,#addbike:hidden').show();
                }


                if (nma < 1) {
                    $('#assetsTable tr:first').hide();
                }
                else {
                    $('#assetsTable tr:first').show();
                }
            

        } else {

            alert('You need to submit at least one asset');
        }
        

    });


    $('#assetsTable').on('click', '.bikeClose', function () {

 
		var nPA = $('input[name=NumberPeopleApplying]:checked').val();
		var Filledform = $('input[name=Filledform]:checked').val();

		var allowRemove = false;
		
		 if(totalNoAssets()>>1){
			allowRemove = true; 
		}else{
			if (nPA == 2 && Filledform =='Yes'){
			allowRemove = true;
		}
		}
		

        if (allowRemove) {
       



                $(".bikeContainer").hide().find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
                $("#addbike").show();
                $('#nob').val(0);


                var nma = totalbikeVehicle();


                if (nma <= 3) {
                    $('#addmorevehicle:hidden,#addbike:hidden').show();
                }

                if (nma < 1) {
                    $('#assetsTable tr:first').hide();
                }
                else {
                    $('#assetsTable tr:first').show();
                }


          

        } else {

            alert('You need to submit at least one asset');
        }

        
    });

    $(document).on('click', '.infoBox', function (e) {


        if ($("#vehicleEvaluate").dialog("isOpen") == false) {
            $("#vehicleEvaluate").dialog("open")
        } else {
            $("#vehicleEvaluate").dialog("close")
        };

        //$("#vehicleEvaluate").dialog('open');
    })

    $('#assetsTable').on('click', '.propertyClose', function () {

		var nPA = $('input[name=NumberPeopleApplying]:checked').val();
		var Filledform = $('input[name=Filledform]:checked').val();
		var residentialStatus = $('#ResidentialStatus1').val();

		var allowRemove = false; 
		
		if(totalNoAssets()>>1){
			allowRemove = true;
		}else{
			if (nPA == 2 && Filledform =='Yes'){
			allowRemove = true; 
			}
		}
		
		/*if (nPA == 2 && Filledform =='No'){
			allowRemove = true; 
		}else if(totalNoAssets()>>1){
			allowRemove = true;
		}else if(residentialStatus =='I own my home outright' || residentialStatus == 'I have a mortgage'){
			allowRemove = true;
		}
*/		

        if (allowRemove) {



                var Id = $(this).attr('id');
                var j = Id.substr(Id.length - 1);
                var n = j - 1

                if (n < 6) {
                    $('#addmoreproperty:hidden').show();
                }

                if (n >= 1) {

                    $(this).closest('table').remove();
                    $('.mortgageContainer:last').remove();
                    $('#Aop').val(n);

                    $('.recontainer:last .propertyClose').show();


                }

                else {

                    $(this).closest('table').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
                    $('.mortgageContainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", 'disabled');
                    $('#propertyHead').hide();
                    $('#Aop').val(0);

                }

                totalpaymentCalculation();
            
        } else {

            alert('You need to submit at least one asset');
        }
        
    });

    $('#assetsTable').on('click', '.regClose', function () {
        j = $(this).closest('tr').siblings('tr.newRegRow').length;



        if (j < 4) {
            $(this).closest('table').prev('.addmorereg').show();
        }
        $(this).closest('tr').remove();
        
    });
    //var newrrhtml = $('.newRegRow:last').html();
    //$('.newRegRow:last').html(newrrhtml.replace(/{m}/g,'1'));
    $('#assetsTable').on('click', '.addmorereg', function () {
        var newrrhtml = "		<tr class='newRegRow' id='regrow{n}{m}'><td align='left' valign='middle'><select name='Property{n}Register{m}' id='Property{n}Register{m}' class='required'><option value='' selected='selected'>-Select-</option><option value='Mortgage'>Mortgage</option><option value='Caveat' title='Caveat'>Caveat</option></select></td><td><input name='Property{n}OtherMortgage{m}' type='text' id='Property{n}OtherMortgage{m}' class='required currency phly' size='12' placeholder='$'><img src='../images/icon-remove.png' alt='remove' hspace='4' vspace='4'  class='regClose' id='regClose{m}'></td></tr>";
        Id = $(this).attr('id');
        var n = Id.substr(Id.length - 1);
        j = $(this).next('table').find('tr.newRegRow').length;

        m = j + 1;
        newrrhtml = newrrhtml.replace(/{n}/g, n);
        newrrhtml = newrrhtml.replace(/{m}/g, m);
        ptype = $(':selected', '#PurposeOfLoan1').closest('optgroup').attr('label');

        if (ptype == 'Business') {
            //newrrhtml = newrrhtml.replace(/required/g, m); 
        }

        if (m <= 4) {
            $(this).next('table').find('tbody').show().append(newrrhtml);
        }
        if (m > 3) {
            $(this).hide();
        }

        
    });



    $('#assetsTable').on("blur", '.propertyValue', function () {
        var Id = $(this).attr('id');
        var value = makeNumber($(this).val());
        var d = value.toString().length;
        if (d < 5 && value > 0) {
            var p = 5 - d;
            value = value * Math.pow(10, p);
            var newValue = toCurrency(value);
            $("#valueConfirm").data({
                'element': Id,
                'newValue': newValue
            }).dialog("open");
        }



    });
    $('#assetsTable').on("blur", '.PropertyDebt1st', function () {
        var Id = $(this).attr('id');
        var j = Id.charAt(8);
        var value = makeNumber($(this).val());
        var pvalue = makeNumber($('#Property' + j + 'Value').val());
        if (value!='' && pvalue!='' && value >= pvalue  ) {
            $("#morgagevalueConfirm").data({
                'element': Id
            }).dialog("open");
        }



    });


    $("#valueConfirm").on("dialogopen", function (event, ui) {

        var newValue = $(this).data('newValue');

        $('span', this).html(newValue);


    });


    $('#assetsTable').on("click", '.motorFinanceYes', function () {
        var Id = $(this).attr('id');
        $("#vechicleConfirm").data('motorFinance', Id).dialog("open")
    });

    $('#assetsTable').on("click", '.motorFinanceNo', function () {
        var Id = $(this).attr('id');
        var i = Id.charAt(5);
        $('#Vehicle' + i + 'Payment,#Vehicle' + i + 'Bank').hide(500);

    });


    $('#assetsTable').on("click", '.moarryes', function () {
        var Id = $(this).attr('id');
        var j = Id.substr(Id.length - 1);
        $('#monarr' + j + 'months').show('500').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
        

    });

	
	$('#assetsTable').on("click", '.motorFinanceYes', function () {
        var Id = $(this).attr('id');
        $("#vechicleConfirm").data('motorFinance', Id).dialog("open")
    });

    //mortgage rows update on blur
    $('#assetsTable').on("blur", '.PropertyDebt1st,.PropertyBank', function () {
        var Id = $(this).attr('id');
        var i = Id.charAt(8);
        mortgageUpdate(i);
    });

    $('#assetLiability').on('blur', '.MortgageOwing,.MortgageBank', function () {


        var Id = $(this).attr('id');
        var i = Id.substr(Id.length - 1);

        assetUpdate(i);
    })


$('#businessStage').change(function(e) {
	var aop= ($('#Aop').val());
    var v=$(this).val();
	if(v=="Established – Operated for over 12 months"){
		if( $('#Motor1FinanceNo').is(':checked')==false && $('#Motor2FinanceNo').is(':checked')==false && $('#Motor3FinanceNo').is(':checked')==false && $('#Motor4FinanceNo').is(':checked')==false && $('#Motor1FinanceNo').is(':checked')==false && $('#BikeFinanceNo1').is(':checked')==false && aop==0 )	
			$('.usbrow').show().find(":input,textarea,select").addClass('required');
	}
	else{
			$('.usbrow').hide().find(":input,textarea,select").val('').removeClass('required');
	}
	
});




    $('#entityType').on('change', function () {
        var toe = $(this).val();

        if (toe == 'Partnership' || toe == 'Company' || toe == 'Trust' || toe == 'Company as Trustee') {

            $('.businessDirectors').show(500).find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

            var bdname = 'Directors';

            if (toe == 'Partnership') {
                bdname = 'Partners';
				$('#BeneficiaryNameRow').hide(500).addClass('wizard-ignore').attr('disabled', 'disabled');;
            } else if (toe == 'Company') {
                bdname = 'Directors';
				$('#BeneficiaryNameRow').hide(500).addClass('wizard-ignore').attr('disabled', 'disabled');;
            } else if (toe == 'Trust' || toe == 'Company as Trustee') {
                bdname = 'Trustees';
				$('#BeneficiaryNameRow').show(500).removeClass('wizard-ignore').removeAttr('disabled');
            }

            $('#bdname').text(bdname);

        } else {
			$('#BeneficiaryNameRow').hide(500).addClass('wizard-ignore').attr('disabled', 'disabled');;
            $('.businessDirectors').hide(500).find(':input,select,textarea').addClass('wizard-ignore').attr('disabled', 'disabled');
        }

    });



    $('.typeofEmployement').on("change", function () {
        var toe = $(this).val();
		id = $(this).attr('id');
         var i = id.substr(id.length - 1);

        if (toe != '' && toe != 'Centrelink') {
            if (toe == 'Employee') {

                $(this).parents('.fieldrow').next('.employmenttype').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled').addClass('required');
            }
            else {
                $(this).parents('.fieldrow').next('.employmenttype').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error required').attr('disabled');
            }
            $(this).parents('.fieldrow').nextAll('.employeeDetails').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');

            $(this).parents('.fieldrow').nextAll('.selfEmployee').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled')



        }
        else {

            $(this).parents('.fieldrow').nextAll('.employeeDetails').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled')
            $(this).parents('.fieldrow').next('.employmenttype').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled');

           /* if (toe == 'Self-Employed' || toe == 'Company Director') {


                $(this).parents('.fieldrow').nextAll('.selfEmployee').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
                if (toe == 'Company Director') {

                    $(this).parents('.fieldrow').nextAll('.selfEmployee').find('.directorNames').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
                }
                else {
                    $(this).parents('.fieldrow').nextAll('.selfEmployee').find('.directorNames').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
                }

            }
            else {
                $(this).parents('.fieldrow').nextAll('.selfEmployee').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
            }
*/


        }


        // for work income
        if (toe == '' || toe == 'Centrelink') {
			
			            $(this).parents('.employmentDetails').siblings('.workIncome').hide('1000').find(':input,select,textarea').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
        }
        else {

            $(this).parents('.employmentDetails').nextAll('.workIncome').show('1000').find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');;
        }

        //centerlink pension madatory{
        if (toe == 'CentrelinkAndWorkincome' || toe == 'Centrelink') {
            

            $('#CentrelinkIncome' + i).addClass('required').valid();


        } else {
			

            $('#CentrelinkIncome' + i).removeClass('required error').addClass('valid').removeAttr('disabled');  
        }


        
    });

    //centrelinkIncome warning
    $('#CentrelinkIncome1,#CentrelinkIncome2').focusin(function () {
        id = $(this).attr('id');

        var i = id.substr(id.length - 1);
        ptype = $(':selected', '#PurposeOfLoan1').closest('optgroup').attr('label');
        income = $('#TypeOfEmployment' + i).val();
        if (ptype == 'Personal' && income == 'Centrelink') {

            $('#centrelinkWarning').dialog({
                position: {
                    my: "left bottom",
                    at: "right top",
                    of: $(this)
                }
            });
            $('#centrelinkWarning').dialog('open');
        }




    })
    //Total Income
    $('.incomeperiod').on("change", function () {
        totalincomeCalculation();
    });





    $('#IncomeExpense').on('load', '#multiExit', function () {

        alert($(this).attr('id'));
    })

    /*$('#ExitStrategy1').multiselect({
        selectedList: true,
        header: false,
        create: function (event, ui) {
        }

    });*/


    $('#ExitStrategy1').on("change", function () {

        var sItems = $(this).val();

        //stageOfProperty
        if ($.inArray("Sale of real estate property", sItems) != -1) {

            $(this).parents('.fieldrow').next('.stageOfProperty').show('1000').find(':input').removeClass('wizard-ignore').removeAttr('disabled');
        }
        else {
            $(this).parents('.fieldrow').next('.stageOfProperty').hide('1000').find(':input').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
        }


        //stageOfRefinance
        if ($.inArray("Refinancing", sItems) != -1) {

            $(this).parents('.fieldrow').nextAll('.stageOfRefinance').show('1000').find(':input').removeClass('wizard-ignore').removeAttr('disabled');
        }
        else {
            $(this).parents('.fieldrow').nextAll('.stageOfRefinance').hide('1000').find(':input').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
        }


        //otherSpecify
        if ($.inArray("Others", sItems) != -1) {

            $(this).parents('.fieldrow').nextAll('.otherSpecify').show('1000').find(':input').removeClass('wizard-ignore').removeAttr('disabled');
        }
        else {
            $(this).parents('.fieldrow').nextAll('.otherSpecify').hide('1000').find(':input').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
        }

        
        $(this).valid();

    });





    $('.chistory').change(function () {
        var choice = $(this).val(); 
        var Id = $(this).attr('id');
        var j = Id.substr(Id.length - 1);

        if (choice == '1 default' || choice == '2 defaults' || choice == '3 or more defaults') {

            $('#1defaulthtml' + j).show('1000').find(':input,textarea,select').removeClass('wizard-ignore').removeAttr('disabled');

            if (choice == '2 defaults' || choice == '3 or more defaults') {

                $('#2defaulthtml' + j).show('1000').find(':input,textarea,select').removeClass('wizard-ignore').removeAttr('disabled');

            }
            else {

                $('#2defaulthtml' + j).hide('1000').find(':input,textarea,select').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
            }


        }
        else {

            $('#1defaulthtml' + j).hide('1000').find(':input,textarea,select').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
            $('#2defaulthtml' + j).hide('1000').find(':input,textarea,select').addClass('wizard-ignore').removeClass('error').attr('disabled', 'disabled');
            $('#more').remove();
        }

        if (choice == 'Ex-bankrupt' || choice == 'Past Part IX debt agreement') {
            $('.xbankrupt').fadeIn('1000').find(':input,textarea,select').removeClass("wizard-ignore").removeAttr("disabled");

        }
        else {
            $('.xbankrupt').fadeOut('1000').find(":input,textarea,select").addClass("wizard-ignore").removeClass('error').attr('disabled', 'disabled');
        }

        

    });


    jQuery.validator.addMethod("defaultValue", function (value, element) {

        return this.optional(element) || value != 'The business purpose intended for this loan is ';
    }, "*");

	

    jQuery.validator.addMethod("landPhone", function (phone_number, element) {
        // phone_number = phone_number.replace(/\s+/g, ""); 
       //return this.optional(element) || phone_number.length <= 12 && phone_number.match(/^[0][1-9]\d{2}\s\d{4}\s\d{4}$/);
	 
	   if( phone_number.length == 9 ){ 
		   return phone_number.match(/^\d{4}\s\d{4}$/)
	   }
	   else if(phone_number.length == 12){
		     return phone_number.match(/^[0][1-9]\s\d{4}\s\d{4}$/)
	   }
	   else if(phone_number.length == 0){
		     return phone_number.match(/^\s*$/)
	   }
	   
	    
    }, "please enter the correct Home phone number");   
	
	
	

    jQuery.validator.addMethod("mobilePhone", function (mobile_number, element) {
        // phone_number = phone_number.replace(/\s+/g, ""); 
        return this.optional(element) || mobile_number.length <= 12 && mobile_number.match(/^[0][4]\d{2}\s\d{3}\s\d{3}$/);
    }, "please enter the correct mobile phone number");
	
	jQuery.validator.addMethod("postCode", function (pcode, element) {
        // phone_number = phone_number.replace(/\s+/g, ""); 
        return this.optional(element) || pcode.length <= 4 && pcode.match(/^[2-9]\d{3}$/);
    }, "please enter the correct postcode");
	

    jQuery.validator.addMethod("currencyNumber", function (cur_number, element) {
        cur_number = cur_number.replace(/\,+/g, "");
        //alert(cur_number);
        return this.optional(element) || cur_number.match(/\d/);
    }, "Please specify a valid amount");

    jQuery.validator.addMethod("minAmt", function (cur_number, element) {
        cur_number = cur_number.replace(/\,+/g, "");
        //alert(cur_number);
        if (cur_number.match(/\d/)) {
            return this.optional(element) || cur_number > 0;
        }
    }, "Please specify a valid amount");


    jQuery.validator.addMethod("maxAmount", function (ln_number, element) {
        ln_number = new Number(ln_number.replace(/\,+/g, ""));
        minamt = new Number(1000);
        amt = new Number(100000000);
        if (ln_number < amt) {

            return this.optional(element) || ln_number >= minamt
        }

    }, "Please specify a valid Loan amount");

    jQuery.validator.addMethod("date", function (birthday, element) {

        var maxDate = (18).years().ago();
        var minDate = (90).years().ago();
        var DOB = Date.parse(birthday);
        // if((DOB <= today && DOB >= minDate)) {  
        if (birthday.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
            d = birthday.split('/');
            if (d[0] <= 31 && d[1] <= 12) {
                return this.optional(element) || DOB >= minDate && DOB <= maxDate;
            }
        }

    }, "Please enter a valid Date of Birth in dd/mm/yyyy format");

    /*jQuery.validator.addMethod("placeholder", function(value, element) {
  return value==$(element).attr("placeholder");

}, '');
*/

    jQuery.validator.addClassRules({
        Phone: {
            landPhone: true,			
           required: function (element) {
                id = $(element).attr('id');
                var i = id.substr(id.length - 1);
                //return $('#Mobile' + i).val() == '';
				if($('#Mobile' + i).val() == '')
               		return true;
				else
					return false;
            }
        },
        Mobile: {
            mobilePhone: true,
			//uniqueMobile : true,
            required: function (element) {
                id = $(element).attr('id');
                var i = id.substr(id.length - 1);
                //return $('#Phone' + i).val() == '';
				if($('#Phone' + i).val() == '')
               		return true;
				else
					return false;
            }
		},
		Postcode: {
			postCode: true,
			required: function (element) {
                id = $(element).attr('id');
                return $('#Postcode1').val() == '';
            }
			
		},
				
		/*otherIncome:{
			
			required:function(element){
				return $(element).parent('.fieldrow').find('.otherIncome').val!='';
			}
		},
*/
 currency: {
            currencyNumber: true
        },
        dateOfBirth1: {
            date: true
        },
        minAmt: {
            minAmt: true
        },
		uniqueEmailClass : {  
			remote: {
				url: "includes/validation.php",
				type: "post",
				data: {
						submiting:'emailValidation'
					   }
				}
		},
		
		uniquePhoneClass : {  
			remote: {
				url: "includes/validation.php",
				type: "post",
				data: {
						submiting:'phoneValidation'
					   }
				}
		},
		uniqueMobileClass : {
			remote: {
				url: "includes/validation.php",
				type: "post",
				data: {
						submiting:'mobileValidation'
					   }
				}
			//uniqueMobile : true,
		},
		
		
		
		checkPwdClass : {
			remote: {
				url: "../includes/validation.php", 
				type: "post",
				data: {
						submiting:'checkCurrentPwd'
					   }
				}
			//uniqueMobile : true,
		},
       
    });

    //$('.navigation_button').button(); 

    //init tooltips
	
	 $("[data-toggle='tooltip']").tooltip();
    /*$('#formApp').on('mouseover', '.infoTip', function () {
        var tooltips = $("img[title].infoTip").tooltip();
    });
*/

	$("#formProfile").validate({
							   
		errorPlacement: function (error, element) {

                if ($(element).hasClass('checkPwdClass')) {
                    error.appendTo(element.parents('.control-group'));
					document.getElementById("chagepwd").disabled=true;
                } 
				
				
				

            },
            highlight: function (element, errorClass, validClass) {

                $(element).parent('.control-group').addClass(errorClass).removeClass(validClass);
				
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parent('.control-group').addClass(validClass).removeClass(errorClass);
               
            }
		 
	});
	
	$('#currentpassword').blur(function(){
		if($(this).valid())			
			document.getElementById("chagepwd").disabled=false;
	});
	$("#formProfile").submit(function(e){
									 
	//$.blockUI(); 
	if($(this).valid())
	
	{
		
		document.getElementById("chagepwd").disabled=false;
		return true;
	}
	else
	{
		document.getElementById("chagepwd").disabled=true;
		e.preventDefault();
	}
									  
	}); 
	$("#formPersonal").submit(function(e){
		 
		if($(this).valid())
		{
			return true;
		}
		else
		{ 
			e.preventDefault();
		}
										  
		});
	/*$('#showBUI').click(function(){
								 
   if(rmoney == 'requestmoney')
   {
	   var proBar = '../assets/img/progress_bar.gif';
   }
   else
   {
	   var proBar = 'assets/img/progress_bar.gif';
   }
    
		$.blockUI({ message: '<img src="'+ proBar +'" />' });
		setTimeout($.unblockUI, 2000); 						 
	});*/
	
    $('#formApp').submit(function (e) {
								   
		
		
        if ($(this).valid()) {
			 /* if(rmoney != '' && rmoney != null && rmoney == 'requestmoney')
			   {
				   proBar = '../assets/img/progress_bar.gif';
			   }
			   else  if(rmoney != '' && rmoney != null && rmoney == 'applynow')
			   {
				   proBar = 'assets/img/progress_bar.gif';
			   }
			
			  alert(proBar);    
           $.blockUI({ message: '<img src="'+ proBar +'" />' }); 
			setTimeout($.unblockUI, 10000); */
            v = $('#nos').val();
           	localStorage.clear();
		
            v++;
            $('#nos').val(v);

        } else {
            e.preventDefault();

        }

    })
	$('#PayslipCheck, #IDCheck').validate({
	errorPlacement: function(error, element){},
	rules: {
	photo: {
	required: true,
	extension: "docx|doc|pdf"
	},
	highlight: function(input) {
            $('#photo_upload').css('border-color', '#F00');
			
        },
	}
	});
	$('#PayslipCheck, #IDCheck').submit(function(e){
								   
		if($(this).valid())
		{
			$.blockUI({ message: '<h1><img src="ajax-loader.gif" /> please wait...</h1>' });
			
		}
		else
		{   
			e.preventDefault();
			alert('please select file to upload or email');
		}
	});
	
	




    //init modal window

    $("#quickReference").dialog({
        autoOpen: false,
        minWidth: 820,
        modal: true
    });



     $("#centrelinkWarning").dialog({
        autoOpen: false,
        minHeight: 160,
        minWidth: 450,
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        },
		 buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        }
    })
	
    $("#visaDialog").dialog({
        autoOpen: false,
        minHeight: 160,
        minWidth: 300,
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        }
    });

    $("#submitConfirm").dialog({
        autoOpen: false,
        minHeight: 160,
        minWidth: 300,
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        }
    });

    $("#vehicleEvaluate").dialog({
        autoOpen: false,
        position: {
            my: "left bottom",
            at: "right top",
            of: '.infoBox'
        },
        title: 'Check Value of your Vehicle',
        height: 200,
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        }

    });

    $("#vechicleConfirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "Yes": function () {
                $(this).dialog("close");
                var yesId = $(this).data('element');
                var noId = yesId.replace('Yes', 'No');
                $('#' + yesId).prop("checked", true);
                $('#' + noId).removeAttr('checked');
                iD = yesId.charAt(5);
                $('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').show(500);

            },
            "No": function () {

                $(this).dialog("close");
                var yesId = $(this).data('motorFinance');
                var noId = yesId.replace('Yes', 'No');
                $('#' + noId).prop("checked", true);
                $('#' + yesId).removeAttr('checked');
                iD = yesId.charAt(5);
                $('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').hide(500);
                //$('input[name=Motor1Finance]').val('[No]');
            }
        }
    });
	$('.HardshipYes').on("click",function () {
        var Id = $(this).attr('id');
        $("#HardshipConfirm").data('hardship', Id).dialog("open");
    });
	$('.GamblingYes').on("click",function () {
        var Id = $(this).attr('id');
		$("#GamblingConfirm").data('gambling', Id).dialog("open")
    });

    $("#HardshipConfirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "Yes": function () {
                $(this).dialog("close");
                var yesId = $(this).data('hardship');
				var noId = yesId.replace('Yes', 'No');
                $('#' + yesId).prop("checked", true);
                $('#' + noId).removeAttr('checked');
               // iD = yesId.charAt(5);
               // $('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').show(500);

            },
            "No": function () {

                $(this).dialog("close");
                var yesId = $(this).data('hardship');
                var noId = yesId.replace('Yes', 'No');
                $('#' + noId).prop("checked", true);
                $('#' + yesId).removeAttr('checked');
               // iD = yesId.charAt(5);
                //$('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').hide(500);
                //$('input[name=Motor1Finance]').val('[No]');
            }
        }
    });
	$("#GamblingConfirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "Yes": function () {
                $(this).dialog("close");
                var yesId = $(this).data('gambling');
                var noId = yesId.replace('Yes', 'No');
                $('#' + yesId).prop("checked", true);
                $('#' + noId).removeAttr('checked');
               // iD = yesId.charAt(5);
               // $('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').show(500);

            }, 
            "No": function () {

                $(this).dialog("close");
                var yesId = $(this).data('gambling');
                var noId = yesId.replace('Yes', 'No');
                $('#' + noId).prop("checked", true);
                $('#' + yesId).removeAttr('checked');
                iD = yesId.charAt(5);
                //$('#Vehicle' + iD + 'Payment,#Vehicle' + iD + 'Bank').hide(500);
                //$('input[name=Motor1Finance]').val('[No]');
            }
        }
    });

    $("#valueConfirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 140,
        modal: false,
        title: 'Confirm',
        buttons: {
            "Yes": function () {
                $(this).dialog("close");
                var obj = $(this).data('element');
                var newVal = $(this).data('newValue');
                $('#' + obj).val(toCurrency(newVal));



            },
            "No": function () {

                $(this).dialog("close");

            }
        },
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        }
    });

    $("#morgagevalueConfirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 150,
        modal: false,
        title: 'Confirm',
        buttons: {
            "Yes": function () {
                $(this).dialog("close");



            },
            "No": function () {
                $(this).dialog("close");
                var obj = $(this).data('element');
                $('#' + obj).val('');
            }
        },
        open: function () {
            $(this).parents('.ui-dialog').bgiframe();
        }
    });

    $('#launchCalc').click(function () {
        $("#quickReference").dialog("open");
    });
	
	 $("#addmorePloan").click(function () {
       
		 $('.ploanContainer:hidden').show();
        $(this).hide();
        
    });
    $("#liabilityTable").on("click", ".ploanClose", function () {
		 $('.ploanContainer').hide();
		
        $('#addmorePloan').show();
		
        totalpaymentCalculation();
    });
	
	
	 $("#addmoreccard").click(function () {
       
       $('.ccardContainer:hidden').show();
	 $('#addmoreccard').hide();
        
    });
    $("#liabilityTable").on("click", ".ccardClose", function () {
		 $('.ccardContainer').hide();
		
        $('#addmoreccard').show();
		totalpaymentCalculation();
    });
	
	
	 $("#addmorePayday").click(function () {
       
         $('.paydayContainer:hidden').show();
		 $(this).hide();
    });
    $("#liabilityTable").on("click", ".paydayClose", function () {
		 $('.paydayContainer').hide();
		
        $('#addmorePayday').show();
		
        totalpaymentCalculation();
    });


	

    $("#liabilityTable tr:nth-child(even)").css("background-color", "#F3F5FA");

    $("#addmoreloan").click(function () {
        $("#liabilityTable tr:nth-child(even)").css("background-color", "#F3F5FA");


        var n = makeNumber($("#nol").val());
        if (n < 4) {
            var newRow = '<tr><td align=right><input type="text" id=OtherLoan{n} name=Liabilities[OtherLoan{n}][type] class=required /></td><td align=center><input type=text id=OtherLoanOwing{n} name=Liabilities[OtherLoan{n}][owing] class=required /></td><td align=center><input type=text id=OtherLoanPayment{n} name=Liabilities[OtherLoan{n}][payment] onblur=totalpaymentCalculation()  class=required /></td><td align=center><input type=text id=OtherLoanBank{n} name=Liabilities[OtherLoan{n}][bank] class=required /></td><td><img src="../images/icon-remove.png" alt="remove"  hspace="4" vspace="4" align="right" class="loanclose" /></td></tr>';

            newRow = newRow.replace(new RegExp('{n}', 'g'), n + 1);
            $("#liabilityTable").append(newRow);
            $("#nol").val(n + 1);
            if (n == 3) $('#addmoreloan').hide();
        }
    });
    $("#liabilityTable").on("click", ".loanclose", function () {
        $(this).closest("tr").remove();
        $('#addmoreloan').show();
        var n = makeNumber($("#nol").val());
        $("#nol").val(n - 1);
        totalpaymentCalculation();
    });


    $('.liabilities').blur(function (e) {
        var hasValue = 0;
        $(this).closest('tr').find('input').each(function () {
            var v = $(this).val();
            //alert (v);
            if (v != "" && v != 0) hasValue = 1;
        });
        if (hasValue == 1) $(this).closest('tr').find('input').addClass('required');
        else $(this).closest('tr').find('input').removeClass('required error');

    });



    $("#IncomeAfterTax1,#CentrelinkIncome1,#RentalIncome1,#IncomeAfterTax2,#CentrelinkIncome2,#RentalIncome2").blur(function () {
        totalincomeCalculation();
    });



    //hide , show objects

    InitPage();
    $('tbody', '.mvcontainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", "disabled")
    $('tbody', '.bikeContainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", "disabled")
    $('tbody', '.recontainer:last').hide().find(":input,textarea,select").addClass("wizard-ignore").attr("disabled", "disabled")
    $('#help2').hide();
    $('#help3').hide();
	$('#addmorePayday,#addmorePloan,#addmoreccard').hide();
	$('#BeneficiaryNameRow').hide();
	//$('#ui-multiselect-ExitStrategy1-option-0').trigger('click');
    initForm = { 
        historyEnabled: false,
        validationEnabled: true,
        focusFirstInput: true,
        validationOptions: {

            rules: {
                LoanAmount: {
                    maxAmount: true
                },
                OtherPurpose: {
                    defaultValue: true
                }


            }, 
            errorPlacement: function (error, element) {

                if ($(element).hasClass('Phone') || $(element).hasClass('Mobile') || $(element).hasClass('email')) {
                    error.appendTo(element.parents('.control-group'));
                } 
				
				/*if ($(element).hasClass('Phone') || $(element).hasClass('Mobile') || $(element).hasClass('email')) {
                    error.appendTo(element.parents('.control-group'));
                } */
				
				//alert($(element).attr('id'));  
				
				
/*					var L = element.parents('.field').length;
					var k = element.parents('td').length;

					if (L > 0) {
						error.appendTo(element.parents('.field'));
						element.css('display', 'inline');
					}
					else if (k > 0) {
						error.appendTo(element.closest('td'));
					}
*/

            },
            highlight: function (element, errorClass, validClass) {

                $(element).parent('.control-group').addClass(errorClass).removeClass(validClass);
				
				
				
               /* if ($(element).attr('type') != 'text' && !$(element).is('select') && !$(element).is('textarea')) {
                    $(element).parent().addClass(errorClass).removeClass(validClass);
                } 
                else {
                    $(element).addClass(errorClass).removeClass(validClass);
                }

                if ($(element).attr('id') == 'ExitStrategy1') {
                    $(element).parent().addClass(errorClass).removeClass(validClass);
                }
                else {
                    $(element).addClass(errorClass).removeClass(validClass);
                }*/
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parent('.control-group').addClass(validClass).removeClass(errorClass);
                /*if ($(element).attr('type') != 'text' && !$(element).is('select') && !$(element).is('textarea')) {
                    $(element).parent().removeClass(errorClass).addClass(validClass);
                }
                else {
                    $(element).addClass(validClass).removeClass(errorClass);
                }

                if ($(element).attr('id') == 'ExitStrategy1') {
                    $(element).parent().removeClass(errorClass).addClass(validClass);
                }
                else {
                    $(element).addClass(validClass).removeClass(errorClass);
                }*/
            }
        },
        disableUIStyles: true,
/*inAnimation : {height:'show',},
			outAnimation: {height: 'hide'},
			inDuration : 700,
			outDuration: 700,*/
        easing: 'easeInOutQuart', //see e.g. http://gsgd.co.uk/sandbox/jquery/easing/ for information on easing
		ignoreTitle:true
    }
    $("#formApp").formwizard(initForm); 


/*	$("#formApp").bind("before_step_shown", function(event, data) {
			

}


			
			
		})*/


    $('.otherIncome').blur(function () {
        id = $(this).attr('id');
        i = id.substr(id.length - 1);

        if ($('#OtherIncomeSpecify' + i).val() == '' && $('#RentalIncome' + i).val() == '') {
            $('#OtherIncomeSpecify' + i).removeClass('required').valid();
            $('#RentalIncome' + i).removeClass('required').valid();
        } else {
            $('#OtherIncomeSpecify' + i).addClass('required').valid();
            $('#RentalIncome' + i).addClass('required').valid();
        }
    });

    $('#next').addClass('nxt');
	
	
	
	$("#formApp").bind("before_step_shown", function(event, data){
		action = data.currentStep;
		//$("#formApp").formwizard("state");
		//alert(action);
		//return false;
		if(action == 'done')
		{}
	});

    $("#formApp").bind("step_shown", function (event, data) {
        var totalSteps = $('#formApp .step').length;
        //var s = data.activatedSteps.length;
        var cs = data.currentStep;
        switch (cs) {
        case 'generalDetails':
            progressText = 'You are 5 mins away from finishing';
            s = 1;
            break;
        case 'personalDetails':
            progressText = 'You are 4 mins away from finishing';
            s = 2;
            break;
        case 'assetLiability':
            progressText = 'You are 3 mins away from finishing';
            s = 3;
            break;
        case 'IncomeExpense':
            progressText = 'You are 2 mins away from finishing';
            s = 4;
            break;
        case 'done':
            progressText = 'You are 1 min away from finishing';
            s = 5;
            break;
        }
		
		if (s == 1) {
		$('div:nth-child(2)', '#StepHead').removeClass('legend step2');
		$('div:nth-child(2)', '#StepHead').removeClass('legend step3');
		$('div:nth-child(2)', '#StepHead').addClass('legend step1');
		}
		else if (s == 3) {
		$('div:nth-child(2)', '#StepHead').removeClass('legend step1');
		$('div:nth-child(2)', '#StepHead').removeClass('legend step3');
		$('div:nth-child(2)', '#StepHead').addClass('legend step2');
		}else{
		$('div:nth-child(2)', '#StepHead').removeClass('legend step1');
		$('div:nth-child(2)', '#StepHead').removeClass('legend step2');
		$('div:nth-child(2)', '#StepHead').addClass('legend step3');
		}
        $('#sidenav li').removeClass('active');

        $('#item' + s, '#sidenav').addClass('active', 400);

        if (s == 1) {
            //$('#back').hide().attr('disabled', 'disabled');
			$('#back').css("visibility","hidden").attr('disabled', 'disabled');
			$('#Title2').attr('disabled', 'true');
			$('#Residency2').attr('disabled', 'true');
			//alert("hi");
			
        } else {
            //$('#back').show().removeAttr('disabled');
			$('#back').css("visibility","visible").removeAttr('disabled', 'disabled');
        }

        var percentage = (s / totalSteps) * 100;
        var progressSoFar = $("#progressbar").progressbar('value');


        if (percentage > progressSoFar) {

            diff = progressSoFar + 5;
            newper = '+=' + (percentage - progressSoFar);
            //  alert('forward-'+percentage+'-'+diff+'-'+progressSoFar);
        } else if (percentage < progressSoFar) {
            diff = progressSoFar - 5;
            newper = '-=' + (progressSoFar - percentage);
            // alert('backward-'+percentage+'-'+diff+'-'+progressSoFar);
        }

       /* $("#progressbar").progressbar({
            value: diff,
            change: function () {
                $(".progress-label").text(progressText);
                $('.ui-progressbar-value', this).animate({
                    width: newper + '%',
                    done: function () {
                        // progressSoFar = percentage;  
                    }
                });


            },
            complete: function () {
                $(".progress-label").text("Complete!");
            }
        });*/



        if (data.isLastStep) {
            $('#next').removeClass('nxt').addClass('smt');
        } else {
            $('#next').removeClass('smt').addClass('nxt');
        }

        if (data.isLastStep && !wizard) {
            $('#formApp fieldset').show() //.find(':input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled'); 
            $('#formApp fieldset *:visible').find('input,select,textarea').removeClass('wizard-ignore').removeAttr('disabled');
            $('.ui-multiselect').removeAttr('disabled');

            assetValidate('assetLiability');

            $('#disableWizard').text('Collaspe All Pages');
			$('#Title2').attr('disabled', 'true');
			$('#Residency2').attr('disabled', 'true');
            //$('#back').hide();
			$('#back').css("visibility","hidden");
			location.hash = '#' + data.previousStep;
           // $.unblockUI();
/*$("#status").fadeOut(); // will first fade out the loading animation
            $("#preloader").delay(350).fadeOut("slow"); */
        }


    });




    var cs = 'generalDetails';

    $('#disableWizard').click(function () {

        if (wizard) {

            //$("#formApp").formwizard("destroy");
            //InitPage();
            fs = $("#formApp").formwizard("state");
            cs = fs.currentStep;
           // $.blockUI();
/*$("#status").fadeIn(); // will first fade out the loading animation
            $("#preloader").show(300);
*/
            $('#formApp').formwizard("show", 'done');
            wizard = 0;
        } else {



            $('#formApp').formwizard('update_steps');


            $(this).text('Show All Pages');
            //$('#back').show();
			$('#back').css("visibility","visible");
            wizard = 1;
            $('#formApp').formwizard("show", cs);

            $('#formApp').formwizard('update_steps');


        }
    });
	

		
	
	//boarding fee, only numbers
	/*$("#BoardingRentingFee1,#BoardingRentingFee2").keypress(function(e) {
    	var a = [];
   	 	var k = e.which;
    
   		for (i = 48; i < 58; i++)
        a.push(i);
    
    	if (!(a.indexOf(k)>=0))
       	 e.preventDefault();
	});*/

	$('.decimal').keyup(function(){
   	 var val = $(this).val();
   	 if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    $(this).val(val); 
	});

});

function promptConfirm(){
	
			$( "#dialog-confirm" ).dialog({
			  resizable: false,
			  height:140,
			  modal: true,
			  buttons: {
				"OK": function() {
				  $( this ).dialog( "close" );
				  return true;
				},
				Cancel: function() {
				  $( this ).dialog( "close" );
				  return false;
				}
			  }
			});
		
}


$(document).ready(function(e) {
    $('#ui-multiselect-ExitStrategy1-option-0').trigger('click');
	
	
});

	$(document).on("focusin","#Property1Address,#Property2Address,#Property3Address,#Property4Address,#Property5Address,#Property6Address",function(){
	
					nthobj = $(this).attr('id');
				  var n = nthobj.charAt(8);
				
				 $(this).autocomplete({
				source: "addressify.php", 
				minLength: 3, 
				select: function (event, obj) { 
				
		$.getJSON('getParsedAddress.php?term='+ obj.item.value, function(data) {	

		   
			$('#Property'+n+'Address').val(data.StreetLine+', '+data.Suburb+' '+data.State+' '+data.Postcode).valid();
			$('#Property'+n+'Suburb').val(data.Suburb).valid();
			$('#Property'+n+'State').val(data.State).valid();
			$('#Property'+n+'Postcode').val(data.Postcode).valid();
			
			})
				}
	 });
	 
	 });